package org.tong.web.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.tong.common.domain.dos.ArticleDO;
import org.tong.common.domain.mapper.ArticleMapper;
import org.tong.common.utils.PageResponse;
import org.tong.common.utils.Response;
import org.tong.web.convert.ArticleConvert;
import org.tong.web.model.vo.archive.FindArchiveArticlePageListReqVO;
import org.tong.web.model.vo.archive.FindArchiveArticlePageListRspVO;
import org.tong.web.model.vo.archive.FindArchiveArticleRspVO;
import org.tong.web.service.ArchiveService;

import java.time.YearMonth;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ArchiveServiceImpl implements ArchiveService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Response findArchivePageList(FindArchiveArticlePageListReqVO findArchiveArticlePageListReqVO) {
        Long current = findArchiveArticlePageListReqVO.getCurrent();
        Long size = findArchiveArticlePageListReqVO.getSize();

        Page<ArticleDO> articleDOPage = articleMapper.selectPageList(current, size, null, null, null);
        List<ArticleDO> articleDOS = articleDOPage.getRecords();
        List<FindArchiveArticlePageListRspVO> vos = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(articleDOS)){
            List<FindArchiveArticleRspVO> archiveArticleRspVOS = articleDOS.stream().map(ArticleConvert.INSTANCE::convertDO2ArchiveArticleVO).collect(Collectors.toList());
            Map<YearMonth, List<FindArchiveArticleRspVO>> yearMonthListMap = archiveArticleRspVOS.stream().collect(Collectors.groupingBy(FindArchiveArticleRspVO::getCreateMonth));
            // 使用 TreeMap 按月份倒序排列
            Map<YearMonth, List<FindArchiveArticleRspVO>> sortedMap = new TreeMap<>(Collections.reverseOrder());
            sortedMap.putAll(yearMonthListMap);
            sortedMap.forEach((k,v)->{
                vos.add(FindArchiveArticlePageListRspVO.builder().month(k).articles(v).build());
            });
        }
        return PageResponse.success(articleDOPage,vos);
    }
}
